package by.wind.drebedengi.asynctask;

import by.wind.drebedengi.R;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.DeleteObject;
import by.wind.drebedengi.datalayer.bean.Record;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;

import android.app.ProgressDialog;
import android.content.Context;

public class DeleteAsyncTask extends AbstractTask {

	private String itsType;
	private Record itsRecord;
	
	public DeleteAsyncTask(Context aContext, String aType, Record aRecord) {
		super(aContext);
		itsType = aType;
		itsRecord = aRecord;
		itsProgressMessage = itsContext.getString(R.string.task_delete);
	}

	@Override
	public void setProgressTracker(IProgressTracker progressTracker) {
		// Attach to progress tracker
		itsProgressTracker = progressTracker;
		// Initialize progress tracker with current task state
		if (itsProgressTracker != null) {
			itsProgressTracker.onProgress(itsProgressMessage);
			if (itsResult != null) {
				itsProgressTracker.onComplete();
			}
		}

	}

	@Override
	protected int getProgressType() {
		return ProgressDialog.STYLE_SPINNER;
	}

	@Override
	protected Boolean doInBackground(Long... params) {
		if (isCancelled()) return false;
		if (itsRecord.getServer_id()>0)
			return deleteSavedOnServerRecord();
		else
			return deleteNonSavedOnServerRecord();
	}

	private boolean deleteNonSavedOnServerRecord() {
		MyDatabaseHelper itsHelper = new MyDatabaseHelper(itsContext);
		RuntimeExceptionDao<Record, Integer> dao = itsHelper.getRecordDataDao();
		DeleteBuilder<Record, Integer> deleteBuilder = dao.deleteBuilder();
		try {
			deleteBuilder.where().eq(Record.CLIENT_ID, itsRecord.getClient_id());
			deleteBuilder.delete();
		} catch( Exception ex) {
			ex.printStackTrace();
			return false;
		}
		itsHelper.close();
		return true;
	}
	
	private boolean deleteSavedOnServerRecord() {
		MyDatabaseHelper itsHelper = new MyDatabaseHelper(itsContext);
		if (!this.isNetworkAvailable()) {
			return false;
		}
		try {
			DeleteObject deleteRecord = new DeleteObject(itsRecord.getServer_id(), itsType);
			deleteRecord.loadData();
				
			if (deleteRecord.getResult()) {
				RuntimeExceptionDao<Record, Integer> dao = itsHelper
						.getRecordDataDao();
				DeleteBuilder<Record, Integer> deleteBuilder = dao
						.deleteBuilder();
				deleteBuilder.where().eq(Record.SERVER_ID, itsRecord.getServer_id());
				deleteBuilder.delete();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
		itsHelper.close();
		return true;
	}
	
	@Override
	public String onErrorMessage() {
		// TODO Auto-generated method stub
		if (!this.isNetworkAvailable()) 
			return itsContext.getString(R.string.connection_error);
		else
			return itsContext.getString(R.string.task_delete_error);
	}

}
